//
//  IMMessageTableViewCell.m
//  MLIM
//
//  Created by molon on 15/6/25.
//  Copyright (c) 2015年 molon. All rights reserved.
//

#import "IMMessageTableViewCell.h"
#import "IMMessageBackgroundImageView.h"
#import "IMCommon.h"
#import "IMUserAvatarImageView.h"
#import "IMTextMessage.h"

@interface IMMessageTableViewCell()<UIGestureRecognizerDelegate>

@property (nonatomic, strong) IMMessageBackgroundImageView *backgroundImageView;

@property (nonatomic, strong) IMUserAvatarImageView *avatarImageView;
@property (nonatomic, strong) UILabel *dateLabel;
@property (nonatomic, strong) UIActivityIndicatorView *indicator;
@property (nonatomic, strong) UIImageView *sendFailImageView;

@property (nonatomic, strong) UILongPressGestureRecognizer *backgroundLongPressGesture;
@property (nonatomic, strong) UITapGestureRecognizer *backgroundTapGesture;

@end

@implementation IMMessageTableViewCell
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([gestureRecognizer isEqual:self.backgroundTapGesture]||[gestureRecognizer isEqual:self.backgroundLongPressGesture]) {
        CGPoint location = [touch locationInView:gestureRecognizer.view];
        UIView *view = [gestureRecognizer.view hitTest:location withEvent:nil];
        if ([view isKindOfClass:[MLLinkLabel class]]) {
            if ([((MLLinkLabel*)view) linkAtPoint:[touch locationInView:view]]) {
                return NO;
            }
        }
    }
    return YES;
}

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self resetWithIsInit:YES];
    }
    return self;
}

- (void)dealloc
{
    //移除KVO
    [self.imMessage removeObserver:self forKeyPath:@"status" context:nil];
}

- (void)prepareForReuse
{
    [super prepareForReuse];
    
    [self resetWithIsInit:NO];
}

- (void)resetWithIsInit:(BOOL)isInit
{
    if (isInit) {
        self.backgroundColor = [UIColor clearColor];
        self.contentView.backgroundColor = [UIColor clearColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [self.contentView addSubview:self.dateLabel];
        [self.contentView addSubview:self.backgroundImageView];
        [self.contentView addSubview:self.avatarImageView];
        [self.contentView addSubview:self.indicator];
        [self.contentView addSubview:self.sendFailImageView];
    }
    self.dateLabel.hidden = YES;
    [self.indicator stopAnimating];
    self.sendFailImageView.hidden = YES;
}

#pragma mark - getter
- (IMUserAvatarImageView *)avatarImageView
{
    if (!_avatarImageView) {
        IMUserAvatarImageView *imageView = [[IMUserAvatarImageView alloc]init];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        [imageView activateMLSmoothCornerWithRadius:kAvatarImageViewSideLength/2 andBackgroundColor:IM_AvatarImageBackgroundColor andShouldRasterize:NO];
        
        WEAKSELF
        [imageView setDidTappedAvatarBlock:^(IMUser *imUser) {
            STRONGSELF
            if (sSelf.didTappedAvatarBlock) {
                sSelf.didTappedAvatarBlock(imUser);
            }
        }];
        
        _avatarImageView = imageView;
    }
    return _avatarImageView;
}

- (IMMessageBackgroundImageView *)backgroundImageView
{
    if (!_backgroundImageView) {
        _backgroundImageView = [IMMessageBackgroundImageView new];
        _backgroundImageView.contentMode = UIViewContentModeScaleToFill;
        _backgroundImageView.userInteractionEnabled = YES;
        [_backgroundImageView addGestureRecognizer:self.backgroundLongPressGesture];
        [_backgroundImageView addGestureRecognizer:self.backgroundTapGesture];
    }
    return _backgroundImageView;
}

- (UILabel *)dateLabel
{
    if (!_dateLabel) {
        UILabel* label = [[UILabel alloc]init];
        label.backgroundColor = IMCONFIGM.dateBackgroundColorForIMConversationViewController;
        label.textColor = IMCONFIGM.dateColorForIMConversationViewController;
        label.font = [UIFont systemFontOfSize:11.0f];
        label.layer.cornerRadius = 3.0f;
        label.clipsToBounds = YES;
        label.text = @" ";
        label.textAlignment = NSTextAlignmentCenter;
        
        _dateLabel = label;
    }
    return _dateLabel;
}

- (UIActivityIndicatorView *)indicator
{
    if (!_indicator) {
        _indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        
    }
    return _indicator;
}

- (UIImageView *)sendFailImageView
{
    if (!_sendFailImageView) {
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.image = IMIMG(@"信息发送失败");
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        
        _sendFailImageView = imageView;
    }
    return _sendFailImageView;
}

- (UILongPressGestureRecognizer *)backgroundLongPressGesture
{
    if (!_backgroundLongPressGesture) {
        _backgroundLongPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(backgroundLongPressed:)];
        _backgroundLongPressGesture.delegate = self;
    }
    return _backgroundLongPressGesture;
}

- (UITapGestureRecognizer *)backgroundTapGesture
{
    if (!_backgroundTapGesture) {
        _backgroundTapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backgroundTapped:)];
        _backgroundTapGesture.delegate = self;
    }
    return _backgroundTapGesture;
}

#pragma mark - event
- (void)backgroundLongPressed:(UILongPressGestureRecognizer*)longPressGesture
{
    if (longPressGesture.state == UIGestureRecognizerStateBegan){
        if (self.backgroundImageViewLongPressedBlock) {
            self.backgroundImageViewLongPressedBlock(self);
        }
    }
}

- (void)backgroundTapped:(UITapGestureRecognizer*)tapGesture
{
    if (self.backgroundImageViewTappedBlock) {
        self.backgroundImageViewTappedBlock(self);
    }
}

#pragma mark - gesture delegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer isEqual:self.backgroundLongPressGesture]) {
        //TODO:像判断重试啊，判断是文本消息啊，其实不应该在这里处理，应该留到外面menu那块一块处理才对
        if (!self.backgroundImageViewLongPressedBlock||self.imMessage.status!=IMMessageStatusSendFailed||![self.imMessage isKindOfClass:[IMTextMessage class]]) {
            return NO;
        }
    }else if ([gestureRecognizer isEqual:self.backgroundTapGesture]){
        if (!self.backgroundImageViewTappedBlock) {
            return NO;
        }
    }
    
    return [super gestureRecognizerShouldBegin:gestureRecognizer];
}

#pragma mark - setter
- (void)setImMessage:(IMMessage *)imMessage
{
    //移除之前的
    [_imMessage removeObserver:self forKeyPath:@"status" context:nil];
    
    _imMessage = imMessage;
    
    //添加新的
    [imMessage addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionNew context:nil];
    
    //TODO: 每次都设置没准会影响性能，又必须区分左右，可预留判断再重设置
    [self changeBackgroundImageToDark:NO];
    
    self.dateLabel.text = [[NSDate dateWithTimeIntervalSince1970:imMessage.sendTimestamp]commonChineseStringWithStyle:TimeChineseStringStyleSimple];
    
    self.avatarImageView.clientId = imMessage.clientId;
    
    self.dateLabel.hidden = !imMessage.displayDate;
    
    [self setNeedsLayout];
}

#pragma mark - outcall
- (void)changeBackgroundImageToDark:(BOOL)dark
{
    if (IMISME(self.imMessage.clientId)) {
        self.backgroundImageView.image = [dark?IMIMG(@"Sender暗背景"):IMIMG(@"Sender背景") resizableImageWithCapInsets:IMCONFIGM.senderMessageBackgoundCapInsets];
    }else{
        self.backgroundImageView.image = [dark?IMIMG(@"Receiver暗背景"):IMIMG(@"Receiver背景") resizableImageWithCapInsets:IMCONFIGM.recevierMessageBackgoundCapInsets];
    }
}

#pragma mark - height
+ (CGFloat)heightOfMessage:(IMMessage*)imMessage maxWidth:(CGFloat)maxWidth
{
    return imMessage.displayDate?kMinMessageCellHeight+kDateLabelYMargin*2+kDateLabelHeight:kMinMessageCellHeight;
}

#pragma mark - layout
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    //只设置日期和头像的frame
    
    CGFloat baseY = 0.0f;
    
    if (!self.dateLabel.hidden) {
        CGFloat dateLabelWidth = [self.dateLabel.text singleWidthWithMaxWidth:self.contentView.frameWidth withFont:self.dateLabel.font]+6.0f;
        self.dateLabel.frame = CGRectMake((self.contentView.frameWidth-dateLabelWidth)/2, kDateLabelYMargin, dateLabelWidth, kDateLabelHeight);
        
        baseY = self.dateLabel.frameBottom+kDateLabelYMargin;
    }
    
    if (IMISME(self.imMessage.clientId)) {
        self.avatarImageView.frame = CGRectMake(self.contentView.frameWidth-kElementXSpacing-kAvatarImageViewSideLength, baseY, kAvatarImageViewSideLength, kAvatarImageViewSideLength);
    }else{
        self.avatarImageView.frame = CGRectMake(kElementXSpacing, baseY, kAvatarImageViewSideLength, kAvatarImageViewSideLength);
    }
}

- (void)layoutEnd
{
    if (IMISME(self.imMessage.clientId)) {
        self.indicator.frame = CGRectMake(self.backgroundImageView.frameX-kElementXSpacing-kIndicatorSideLength, self.backgroundImageView.frameY, kIndicatorSideLength, self.backgroundImageView.frameHeight);
        self.sendFailImageView.frame = CGRectMake(self.backgroundImageView.frameX-kElementXSpacing-kSendFailedSignSideLength, self.backgroundImageView.frameY, kSendFailedSignSideLength, self.backgroundImageView.frameHeight);
    }
}

#pragma mark - kvo
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([object isEqual:self.imMessage]&&[@"status" isEqualToString:keyPath]) {
        if (IMISME(self.imMessage.clientId)) {
            if (self.imMessage.status == IMMessageStatusSending) {
                if (![self.indicator isAnimating]) {
                    [self.indicator startAnimating];
                }
            }else{
                if ([self.indicator isAnimating]) {
                    [self.indicator stopAnimating];
                }
            }
            
            self.sendFailImageView.hidden = !(self.imMessage.status == IMMessageStatusSendFailed);
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

@end


@implementation IMMessageTableViewCellLongPressGestureRecognizer

@end